import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Modal, Button, Skeleton, Image, message, Upload, Row, Col, Space, Tag, Tabs, Divider, Slider, InputNumber } from 'antd'
import type { SliderMarks } from 'antd/es/slider';
import { UploadOutlined, LoadingOutlined, CloseOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { information } from '@/utils/rules';
import Utils from 'fr-util/utils';
import type { ProFormInstance } from '@ant-design/pro-components';

import {
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormSelect,
  ProFormDependency,
  ProCard,
  CheckCard,
  ProFormRadio,
  ModalForm,
  ProFormCheckbox
} from '@ant-design/pro-components';

import CheckboxList from './CheckboxList';
import InputNumberItem from './InputNumberItem'


import {
  getTyHerbList,
  reqBaseFormulaCreate,
} from '@/services/firstConsultation';


import styles from '../index.module.less'

const CustomModalAdd = ({
  isOpen,
  user,
  handleModal,
  seletTyDiagnosisIds,
  baseFormulaMap,
  closeModal
}: {
  isOpen: boolean,
  user: any,
  handleModal: Function,
  seletTyDiagnosisIds?: any,
  baseFormulaMap?: any,
  closeModal: Function,
}) => {

  const [formObj] = ProForm.useForm()
  const modalFormRef = useRef<ProFormInstance>();
  const [data, setData] = useState([])

  const [medicineList, setMedicineList] = useState([])

  // useEffect(() => {
  //   if (defArr && defArr?.length > 0 && data && data?.length > 0) {
  //     const initList = defArr.map((item: any) => item?.id)
  //     setSelectList(initList)
  //   }
  // }, [defArr, data])



  async function init(query = {}) {
    const errLogName = '中药材信息列表'
    try {
      const res = await getTyHerbList({ ...query })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        const mapArr = res?.data?.result?.map((item: any) => ({
          medicineId: item?.id,
          label: item?.name,
          quantity: 10
        }))
        // return mapArr;
        // return res?.data?.result
        setData(mapArr)

      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }




  useEffect(() => {
    init()
  }, [])


  async function onFinish(values: any) {
    console.log('onFinish====> :>> ', values);
    // const { cookingTime2, ...other } = values;
    const errLogName = '添加汤剂'
    try {
      const res = await reqBaseFormulaCreate({
        type: 3,
        herbList: medicineList?.map((item: any) => ({
          tyHerbId: item?.medicineId,
          quantity: item?.quantity
        })),
        ...values
      });
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        message.success(`${errLogName}成功`)
        handleModal(false)
        closeModal(false)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }

  const marks: SliderMarks = {
    0: '50%',
    50: '100%',
    150: '200%',
  };


  function onChangeCheckboxList(array: any) {
    console.log('onChangeCheckboxList :>> ', array);
    setMedicineList(array)
  }


  // console.log('baseFormulaMap :>> ', baseFormulaMap);

  return (
    <Modal
      width={'80vw'}
      style={{
        minHeight: '60vh'
      }}
      title="添加自拟方"
      open={isOpen}
      onCancel={() => handleModal(false)}
      footer={null}
      destroyOnClose={true}
    >
      <div>
        <ProForm
          form={formObj}
          layout="horizontal"
          onFinish={(values): Promise<any> => onFinish(values)}
          submitter={{
            // 配置按钮文本
            searchConfig: {
              resetText: '重置',
              submitText: '保存',
            },
          }}
        >
          <Row gutter={24}>
            <Col span={24}>
              <div className={styles.customheader}>
                <ProFormText
                  name="name"
                  label="自拟方名称"
                  placeholder="请输入自拟方名称"
                />
                <Space>
                  <Button type='primary' onClick={() => handleModal(false)}>更换经方</Button>
                  <ModalForm
                    title="增减药材"
                    formRef={modalFormRef}
                    trigger={<Button type='primary'>增减药材</Button>}
                    submitTimeout={1000}
                    width={'80vw'}
                    style={{
                      minHeight: '60vh'
                    }}
                    submitter={{
                      render: (props, defaultDoms) => {
                        return [
                          ...defaultDoms,
                        ];
                      },
                    }}
                    onFinish={async (values) => {
                      // await waitTime(2000);
                      console.log(values);
                      // message.success('提交成功');
                      return true;
                    }}
                  >
                    <CheckboxList data={data} onChange={onChangeCheckboxList} />
                  </ModalForm>
                </Space>
              </div>
            </Col>
            <Col span={24}>
              <Row gutter={24}>
                {
                  medicineList?.map((item, index) => (
                    <Col span={6} key={index}>
                      <InputNumberItem
                        data={medicineList}
                        {...item}
                        index={index}
                        onChange={onChangeCheckboxList}
                      />
                    </Col>
                  ))
                }
              </Row>
            </Col>
          </Row>
          <Divider />
        </ProForm>
      </div>
    </Modal >
  );
};
export default CustomModalAdd;

